
<!DOCTYPE html>
<!--suppress ALL -->
<html lang="zh-cn">
<!--<html lang="en" xmlns:th="http://www.thymeleaf.org">-->
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <title>短信详情</title>
    <script src="/properties/config.js"></script>
    <!-- 默认主题样式 -->
    <link rel="stylesheet" type="text/css" href="/src/css/themes/default.css"/>
    <!-- iview样式 -->
    <link rel="stylesheet" type="text/css" href="/plugins/iview/css/iview.css"/>
    <!--<link rel="stylesheet" type="//unpkg.com/iview/dist/styles/iview.css"/>-->
    <!-- 引入layui样式 -->
    <link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all"/>

    <!-- 引入vue -->
    <script type="text/javascript" src="/plugins/vue/vue.min.js"></script>
    <!--iview js -->
    <script type="text/javascript" src="/plugins/iview/js/iview.js"></script>
    <!--    <script src="//unpkg.com/vue/dist/vue.js"></script>
        <script src="//unpkg.com/iview/dist/iview.min.js"></script>-->

    <!--引入layui.js-->
    <script src="/plugins/layui/layui.js"></script>
    <!--引入axios.js 用于ajax调用-->
    <script src="/plugins/axios/axios.min.js"></script>

    <!-- 流程组件的  -->
    <link rel="stylesheet" href="/Components/ProcessLine/ProcessLine.css">
    <script src="/Components/ProcessLine/ProcessLine.js"></script>

    <!--表格样式-->
    <link rel="stylesheet" href="/Components/Table/Table.css">

    <!-- 引入jQuery，必须在appToken.js 之前引入 -->
    <script src="/build/js/jquery-3.3.1.min.js"></script>
    <!-- 设置全局请求头:app、Authorization -->
    <script src="/build/js/appToken.js"></script>

    <!--引入公共的一些方法-->
    <script src="/src/js/comm.js"></script>


</head>

<style>
#app {
margin: 20px;}
</style>

<body>
<!--隐藏元素--> 
<p id="templateCode"  th:attr="value=${templateCode}"  hidden /> 
<!--使用v-cloak技术，在vue渲染完毕前隐藏页面，渲染完成后显示-->
<div id="app" v-cloak>

      <!--右上侧按钮列表-->
							      
			<div class="ProcessWarp">
			    <Card>
			        <div>
			           <!-- <i-button  slot="extra" type="info"  @click="importTemplateField" style="margin-right:10px">
				          <span>导入字段</span>
				      </i-button> -->
				       <i-button  slot="extra" type="info"  @click="saveTemplate" style="margin-right:10px">
				          <span>保存模板</span>
				      </i-button>
			        </div>
			    </Card>
		    </div>
		    <br>
            <Card>
             <p slot="title">
             	  模板信息
            </p>
            
                 <!--查询表单内容-->
                <row :gutter="16">
	                <i-form ref="templateForm"  :model="templateForm" :rules="templateFormValidate"   label-position="right" :label-width="100">
	                    <i-col span="6">
	                        <form-item label="模板名称：" prop="templateName">
	                            <i-input v-model="templateForm.templateName" placeholder="模板名称" ></i-input>
	                        </form-item>
	                    </i-col>
	                     <i-col span="10">
	                        <form-item label="模板描述：" prop="templateDesc">
	                            <i-input v-model="templateForm.templateDesc" placeholder="模板描述" ></i-input>
	                        </form-item>
	                    </i-col>
                	</i-form>
                </row>
            </Card>
            
       <Modal
                    v-model="selectField"
                    title="导入字段"
                    :mask-closable="false" 
                    width="700">
                       <Transfer
					        :data="fieldList"
					        :target-keys="targetFieldList"
					        :render-format="render"
					        :list-style="fieldListStyle"
					        :titles="['总字段', '选择字段']"
					        :not-found-text="'请选择'"
					        filterable
					        @on-change="handleChange" />
				
				
				<div slot="footer" style="text-align:left">
		            <i-button type="primary" @click="saveTemplateField">
		                <span >保存</span>
		            </i-button>
		            <i-button type="ghost" @click="closeselectFieldModal" style="margin-left: 8px;background-color:rgba(255, 153, 0, 1);color:#ffffff">取消</i-button>
		        </div>
		        
		        
            </Modal>
    
     <!-- 搜索工具框 结束-->
    <!-- 表单Grid，使用layerUI的表格组件 开始 -->
    <row style="padding: 10px" id="fuck">
        <i-col span="24">
            <!-- 使用方法渲染模式 -->
            <table id="listTable" lay-filter="listTable" class="layui-hide"> </table>
           
        </i-col>
    </row>
    
    <!-- 表单Grid，使用layerUI的表格组件 结束 -->
    <!--导出Excel隐藏表单-->
    <iframe id="frame" name="iframe" style="display:none;"></iframe>
    <!--导出Excel隐藏表单-->
</div>

<script type="text/html" id="isViewTpl">
  <input type="checkbox" name="isView" value="{{d.dictCode}}" lay-skin="switch" lay-text="是|否" lay-filter="viewFilter" {{ d.isView == 1 ? 'checked' : '' }}>
</script>

<script type="text/html" id="isMustTpl">
  <input type="checkbox" name="isMust" value="{{d.dictCode}}" title="必须" lay-filter="mustFilter" {{ d.isMust == 1 ? 'checked' : '' }}>
</script>

<script type="text/html" id="barTools">
				{{# if(d.LAY_INDEX == 1){ }}
 					<a class="layui-btn layui-btn-warm layui-btn-xs " lay-event="downTable">下移</a>
					<a class="layui-btn layui-btn-normal layui-btn-xs " style="display: none;" lay-event="upTable">上移</a>
				{{# } else if(d.LAY_INDEX > 1)  { }}
               		<a class="layui-btn layui-btn-normal layui-btn-xs " lay-event="upTable">上移</a>
               	    <a class="layui-btn layui-btn-warm layui-btn-xs " lay-event="downTable">下移</a>
					<a class="layui-btn layui-btn-warm layui-btn-xs " lay-event="upTop">置顶</a>
				{{# } }}
</script>

<script>
/*
* 贷后管理首页 台账 js
*
* */
var templateCode = document.getElementById("templateCode").getAttribute("value");
var layer;
var table;
var basePath;
var vm;
var tableColum;
window.layinit(function (htConfig) {
    var _htConfig = htConfig;
    basePath = _htConfig.coreBasePath;
    uiBasePath = _htConfig.uiBasePath;
    
    getTemplateDetail();
    
    
    vm = new Vue({
        el: '#app',
        data: {
            editSalary:false,
            loading: false,
            exporting: false,//导出标志位
            templateForm: {
            	templateName: '',  //模板名称
            	templateCode: '',  // 模板编码
            	templateDesc: '', // 模板详情
            	templateDetails: [] // 字段详情
            },
            templateFormValidate:{
            	templateName: [
                     { required: true, message: '请输入名称'},
                     { type: 'string', min: 2, max: 10, message: '长度在2到10之间', trigger: 'blur' }
                 ],
                 templateDesc: [
                     { required: true, message: '请输入模板详情'},
                     { type: 'string', max: 50, message: '长度不能超过50', trigger: 'blur' }
                 ]
            },
            
            templateFieldForm: {
            	templateCode:'',
            	resultFields:[]
            },
            selectField:false,
            fieldListStyle:{
            	width: '300px',
                height: '350px'
            },
            fieldList:[],
            targetFieldList:[],
           	
            templateDetailList:[],
        },

        methods: {
            ////  ----   单行操作界面显示  结束 -----------------
            init: function () {
                var self = this;
                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    form = layui.form;
                    //执行渲染
                    var url = basePath + 'salaryTemplate/getTemplateDetailList?templateCode='+ templateCode;
                    $.ajax({
                        type: "GET",
                        url: url,
                        success: function (data) {
                        	console.log("结果data：==",data, arguments);
                        	
                            if (data.code == "0000") {
                            	self.templateDetailList = data.data
                            	table.render({
                                    elem: '#listTable', //指定原始表格元素选择器（推荐id选择器）
                                    id: 'listTable',
                                    limit: 500,
                                    data: self.templateDetailList ,
                                    cols: [[
                                    	{type: 'numbers', align: "center", title: '序号'},
                                        {field: 'dictCode', title: '字段编码', },
                                        {field: 'dictName', title: '字段名称', },
                                        {field: 'isView', title: '是否发送', templet: '#isViewTpl'},
                                        {field: 'isMust', title: '是否必须', templet: '#isMustTpl'},
                                        {fixed: 'right', title: '操作',  align: 'left', toolbar: '#barTools'}
                                    ]], //设置表头
                                    done: function (res, curr, count) {
                                        // 删除最后一行的第一个按钮【上移】
                                        $("#listTable").next().find('table').eq(1).find('tr:last').find('td:last').find('a[lay-event=downTable]').hide();
                                        $("#listTable").next().find('table').eq(3).find('tr:last').find('td:last').find('a[lay-event=downTable]').hide();
                                        var minHeight = $("#fuck").height() + "px";
                                        $("#fuck").css("min-height", minHeight);
                                    }
                                });
                            }else{
                             self.$Modal.error({content: '消息：' + data.msg});
                            }
                        }
                    });
                    
                    table.on('tool(listTable)', function (obj) {
                    	var data = obj.data; 
                        var layEvent = obj.event; 
                        var tr = obj.tr; 
                        var index = tr.index()
                        if(obj.event === 'upTable'){
                           if (index != 0) {
                        	   self.changeArr(self.templateDetailList, index, index - 1);
				               table.reload('listTable', {data: self.templateDetailList })
				            }
                        } else if(obj.event === 'downTable'){
                        	if (index != (self.templateDetailList.length - 1)) {
                        		self.changeArr(self.templateDetailList, index, index + 1);
					            table.reload('listTable', {data: self.templateDetailList })
				            }
				        }else if(obj.event === 'upTop'){
				        	if (index != 0) {
				        		self.changeArr(self.templateDetailList, index, 0);
				                table.reload('listTable', {data: self.templateDetailList })
				           }
				        }
                       
                    });
                    
                    //监听发送操作
                    form.on('switch(viewFilter)', function(obj){
                    	if(self.templateDetailList){
                    		var value = obj.elem.checked ? 1:0 ;
                    		for(var i =0; i< self.templateDetailList.length; i++){
                    			var elementFiled = self.templateDetailList[i];
                    			if(elementFiled.dictCode == obj.value){
                    				elementFiled.isView = value;
                    			}
                    		}
                    	}
                    });
                    
                    //监听必须操作
                    form.on('checkbox(mustFilter)', function(obj){
                    	if(self.templateDetailList){
                    		var value = obj.elem.checked ? 1:0 ;
                    		for(var i =0; i< self.templateDetailList.length; i++){
                    			var elementFiled = self.templateDetailList[i];
                    			if(elementFiled.dictCode == obj.value){
                    				elementFiled.isMust = value;
                    			}
                    		}
                    	}
                    });
                })
            },
            
        	// 查找元素
        	findDictCode:function(details, name, val){
        		console.log("====", details);
        		for (var i = 0; i < details.length; i++) {
	       			if (details[i].dictCode == val && details[i].name == name) {
	       				return i;
	       			}
       			}
       			return -1;
        	},
            
          
            //保存模板
            saveTemplate:function () {
            	var self = this;
            	
            	 var validateFlag = false;
            	 self.$refs["templateForm"].validate(function (valid){
                     if (valid) {
                         validateFlag = true;
                     }
                 });
                 if(!validateFlag){
                     return false;
                 }
            	
            	var url = basePath + "salaryTemplate/saveTemplate" ;
            	
            	if(templateCode != null){
            		self.templateForm.templateCode = templateCode;
            	};
            	if(self.templateDetailList){
            		self.templateForm.templateDetails = self.setArrSort(self.templateDetailList);
            	}
            	var data = JSON.stringify(self.templateForm);
            	$.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (data) {
                        console.log("上传返回参数  ===========",data);
                        if (data.returnCode == "0000") {
                            self.$Modal.success({
                                title: '',
                                content: '操作成功',
                                onOk: function(){
                                	// 关闭当前层
                                	var index = parent.layer.getFrameIndex(window.name);
                                	parent.layer.close(index);
                                },
                            });
                        }else{
                            self.$Modal.error({content: '消息：' + data.msg});
                        }
                        self.toLoadingTime(); 
                    },
                    error:function (data) {
                   	 layer.close(loadingIndex); 
                        self.$Modal.error({content: '操作失败，消息：' + data});
                        self.toLoadingTime();
                    }
                });
				            	
            },
            
            // 导入模板字段
            importTemplateField:function(){
            	var self = this;
            	var totalUrl = basePath + "salaryTemplate/getAllDictParams";
            	
            	
            	self.selectField = true;
            	if(templateCode != null){
            		// 根据模板筛选
            		var selectUrl = basePath + 'salaryTemplate/getTemplateDetailList?templateCode='+templateCode ;
            		 $.ajax({
 	                    type: "GET",
 	                    url: selectUrl,
 	                    contentType: "application/json; charset=utf-8",
 	                    async: false,
 	                    dataType: "json",
 	                    success: function (result) {
 	                    	console.log("目标字段", result.data)
 	                        if (result.code == "0000") {
 	                         var selectedParamList = result.data
 	                       	 for(var i = 0; i< selectedParamList.length; i++ ){
 	                       		self.targetFieldList.push(selectedParamList[i].dictCode);
 	                       		console.log(self.targetFieldList);
 	                       	 }
 	                        }else{
 	                       	 self.$Modal.error({content: '调用接口失败：' + result.msg});
 	                        }
 	                    },
 	                    error:function (data) {
 	                        self.$Modal.error({content: '消息：' + data});
 	                    }
 	
 	                });
            		
            	}
            	
	           	 $.ajax({
	                    type: "GET",
	                    url: totalUrl,
	                    contentType: "application/json; charset=utf-8",
 	                    async: false,
 	                    dataType: "json",
	                    success: function (result) {
	                        console.log("结果：========",result);
	                        if (result.returnCode == "0000") {
	                       	 console.log('所有的字段列表', result.data);
	                         var paramList = result.data
	                       	 for(var i = 0; i< paramList.length; i++ ){
	                       		self.fieldList.push({
	                                key: paramList[i].dictCode,
	                                label: paramList[i].dictName,
	                            });
	                       	 }
	                        }else{
	                       	 self.$Modal.error({content: '调用接口失败：' + result.msg});
	                        }
	                    },
	                    error:function (data) {
	                        self.$Modal.error({content: '消息：' + data});
	                    }
	
	                });
	           	 
	           	 
            	
            },
            
            // 关闭closeselectFieldModal窗口
            closeselectFieldModal:function(){
            	 this.selectField = false
            },
            
            // 显示
            render: function(item) {
                return item.label;
            },
            
            // 修改字段选择事件
            handleChange: function(newTargetKeys, direction, moveKeys) {
                console.log("新的列表：", newTargetKeys);
                this.targetFieldList.length = 0;
                this.targetFieldList = newTargetKeys;
            },
            
            
            // 保存字段的修改
            saveTemplateField: function(){
            	var self = this;
            	var resultFields = self.targetFieldList ;
            	if(resultFields == null || resultFields.length <= 0){
            		self.$Modal.error({content: '请选择模板字段'});
            		return;
            	};
            	
	           
            	
            	var url = basePath + "salaryTemplate/saveTemplateDictParams";
            	if(templateCode != null){
            		self.templateFieldForm.templateCode = templateCode;
            	}
            	self.templateFieldForm.resultFields = resultFields;
            	var data = JSON.stringify(self.templateFieldForm);
            	$.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (data) {
                        console.log("上传返回参数  ===========",data);
                        if (data.returnCode == "0000") {
                        	if(data.data != null){
                        		var result = data.data;
                        		templateCode = result;
                        		self.templateForm.templateCode = result;
                        		self.templateFieldForm.templateCode = result;
                            }
                        	self.selectField = false;
                            self.$Modal.success({
                                title: '',
                                content: '操作成功'
                            });
                            
                        }else{
                            self.$Modal.error({content: '消息：' + data.msg});
                        }
                        self.toLoadingTime(); 
                    },
                    error:function (data) {
                   	 layer.close(loadingIndex); 
                        self.$Modal.error({content: '操作失败，消息：' + data});
                        self.toLoadingTime();
                    }
                });
            	
            },
            
            // 排序
            sortTemplateField: function(currentsort, targetsort, templateDetailId){
            	var self = this;
            	
            	var url = basePath + "salaryTemplate/sortTemplateDictParams";
            	var data = {
            			currentsort : currentsort,
            			targetsort : targetsort,
            			templateDetailId: templateDetailId,
            			templateCode : templateCode 
            	};
            	$.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (data) {
                        console.log("上传返回参数  ===========",data);
                        self.toLoadingTime(); 
                    },
                    error:function (data) {
                        self.$Modal.error({content: '操作失败，消息：' + data});
                        self.toLoadingTime();
                    }
                });
            	
            },
            
            toLoadingTime: function () {
                if (table == null) {
                    return;
                }
                var self = this;
                self.loading = true;
                if(self.templateFieldForm.templateCode != null ){
                	table.reload('listTable');
                }else{
                	
                }
                table.reload('listTable', {
                    where: {
                        templateCode: templateCode,
                    }
                });
            },
            
         // 改变数组位置
           changeArr : function (arr,k,j) {
                var tmp = arr[k];
                arr[k] = arr[j];
                arr[j] = tmp;
                return arr
            },
            
           setArrSort : function(arr){
            	for (var i = 0; i < arr.length; i++) {
        			var array_element = arr[i];
        			array_element.sort = i+1;
        		}
            	return arr;
            },
            // 置顶
            changeTopSort : function(arr,index){
            	console.log("arr:",arr, index);
            	var tmp = [];
            	tmp[0] = arr[index];
            	var tmpIndex = 1;
            	for (var i = 0; i < arr.length; i++) {
            		if(i == index){
            			continue;
            		}
            		tmp[tmpIndex] = arr[i];
            		tmpIndex++;
        		}
            	console.log("tmp:",tmp);
            	arr = tmp;
            	return arr;
            },
            
        },
        mounted:function(){
            this.init();
        }
    });
});



//从后台获取显示数据
var getTemplateDetail = function () {

  //取显示需要的相关信息
  var reqStr = basePath +"salaryTemplate/getTemplateDetail"
  if(templateCode != null){
      reqStr += "?templateCode="+templateCode ;
  }
  axios.get(reqStr)
      .then(function (res) {
         	console.log("模板数据", res.data);
          if (res.data.returnCode == "0") {
          	if(res.data.data != null){
                  vm.templateForm = res.data.data;
              }
          }else {
              vm.$Modal.error({content: '操作失败，消息：' + res.data.msg});
          }
      })
      .catch(function (error) {
          vm.$Modal.error({content: '接口调用异常!'});
      });
}
	
	

</script> 

</body>
</html>